/**
 * 太空飞机大战游戏主入口
 */
import { World, Entity } from './core/ecs';
import { Transform, Renderer, Collider, Health, Weapon, GameState, WaveManager } from './core/components';
import { PlayerShip } from './game/PlayerShip';
import { Input } from './input/Input';
import { FPSMeter } from './utils/FPSMeter';

// 系统导入
import { MovementSystem } from './core/systems/MovementSystem';
import { RenderSystem } from './core/systems/RenderSystem';
import { CollisionSystem } from './core/systems/CollisionSystem';
import { PlayerControlSystem } from './core/systems/PlayerControlSystem';
import { EnemySystem } from './core/systems/EnemySystem';
import { BulletSystem } from './core/systems/BulletSystem';
import { ParticleSystem } from './core/systems/ParticleSystem';
import { WaveSystem } from './core/systems/WaveSystem';
import { UISystem } from './core/systems/UISystem';

class Game {
  private world: World;
  private fpsMeter: FPSMeter;
  private lastTime = 0;
  private isRunning = false;

  constructor() {
    // 初始化Canvas
    const canvas = document.getElementById('game') as HTMLCanvasElement;
    if (!canvas) throw new Error('找不到游戏画布元素');

    const ctx = canvas.getContext('2d');
    if (!ctx) throw new Error('无法获取2D渲染上下文');

    // 设置初始画布大小
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    // 设置canvas可以接收键盘焦点
    canvas.tabIndex = 0;
    canvas.focus();
    
    // 初始化输入系统
    const input = new Input(canvas);

    // 创建世界
    this.world = new World({
      canvas,
      ctx,
      input,
      width: canvas.width,
      height: canvas.height,
      deltaTime: 0
    });

    // 设置窗口大小变化监听
    window.addEventListener('resize', () => this.resizeCanvas(canvas));

    // 初始化FPS计数器
    this.fpsMeter = new FPSMeter();

    // 添加系统
    this.initializeSystems();

    // 创建游戏状态和波次管理器
    this.createGameManagers();
    
    // 创建玩家
    this.createPlayer();

    console.log('🚀 太空飞机大战游戏初始化完成');
  }

  private resizeCanvas(canvas: HTMLCanvasElement): void {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    this.world.resources.width = canvas.width;
    this.world.resources.height = canvas.height;
  }

  private initializeSystems(): void {
    this.world.addSystem(new PlayerControlSystem());
    this.world.addSystem(new EnemySystem());
    this.world.addSystem(new MovementSystem());
    this.world.addSystem(new BulletSystem());
    this.world.addSystem(new CollisionSystem());
    this.world.addSystem(new ParticleSystem());
    this.world.addSystem(new WaveSystem());
    this.world.addSystem(new RenderSystem());
    this.world.addSystem(new UISystem());
  }

  private createGameManagers(): void {
    // 创建游戏状态管理器
    const gameStateEntity = new Entity()
      .addComponent('gameState', GameState());
    
    this.world.addEntity(gameStateEntity);
    
    // 创建波次管理器
    const waveManagerEntity = new Entity()
      .addComponent('waveManager', WaveManager());
    
    this.world.addEntity(waveManagerEntity);
  }

  private createPlayer(): void {
    if (!this.world || !this.world.resources) {
      console.error('World or resources not initialized');
      return;
    }
    
    const { width, height } = this.world.resources;
    
    const player = new Entity()
      .addComponent('transform', Transform(width / 2, height - 100, 0))
      .addComponent('renderer', Renderer('#00ffff', 20, 'triangle'))
      .addComponent('collider', Collider(20, false, 'player'))
      .addComponent('health', Health(100))
      .addComponent('weapon', Weapon(0.2, 25, 800, '#ffff00'))
      .addComponent('player', PlayerShip());

    this.world.addEntity(player);
  }

  /**
   * 启动游戏循环
   */
  start(): void {
    if (this.isRunning) return;
    
    this.isRunning = true;
    this.lastTime = performance.now();
    this.gameLoop();
    
    console.log('🎮 游戏开始运行');
  }

  /**
   * 停止游戏
   */
  stop(): void {
    this.isRunning = false;
    console.log('⏹️ 游戏已停止');
  }

  /**
   * 游戏主循环
   */
  private gameLoop = (): void => {
    if (!this.isRunning) return;

    const currentTime = performance.now();
    const deltaTime = (currentTime - this.lastTime) / 1000; // 转换为秒
    this.lastTime = currentTime;

    // 限制最大帧时间，防止卡顿时出现大跳跃
    const clampedDeltaTime = Math.min(deltaTime, 1/30);

    // 更新FPS
    this.fpsMeter.tick();

    // 更新游戏世界
    this.world.update(clampedDeltaTime);

    // 请求下一帧
    requestAnimationFrame(this.gameLoop);
  };
}

// 游戏启动
document.addEventListener('DOMContentLoaded', () => {
  try {
    const game = new Game();
    game.start();

    // 添加调试信息
    console.log('🎯 控制说明:');
    console.log('  WASD 或 方向键: 移动飞船');
    console.log('  空格键 或 鼠标: 射击');
    console.log('  ESC: 暂停游戏');

    // ESC键暂停功能
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        // TODO: 实现暂停功能
        console.log('暂停功能待实现');
      }
    });

  } catch (error) {
    console.error('❌ 游戏启动失败:', error);
  }
});